<template>
  <div v-permission="'反馈与投诉'" class="warp">
    <div class="warp-content">
      <div class="flex flexBetween">
        <div class="title">请选择订单</div>
        <div class="title">
          <div class="flex flexC">
            <div style="color: #999" @click="openMyDialogRef">选择订单</div>
            <nut-icon
              name="rect-right"
              style="color: #999; font-size: 12px"
            ></nut-icon>
          </div>
        </div>
      </div>
      <template v-for="item in receptData.list">
        <template v-if="item.order_id == currentSelect">
          <template v-if="item.list.length == 1">
            <CARD0 :options="item"></CARD0>
          </template>
          <template v-else-if="item.list.length > 1">
            <CARD1 :options="item"></CARD1>
          </template>
        </template>
      </template>
    </div>
    <div class="container">
      <div class="tips flex flexC flexBetween">
        <div class="flex flexC">
          <div>投诉内容</div>
          <div style="color: red">*</div>
        </div>
        <div class="tips-nums">{{ counts }}/200</div>
      </div>
      <nut-divider style="color: #eeeeee" />
      <div class="container-con">
        <nut-input
          v-model="formData.content"
          style="width: 100% !important"
          :disabled="disabled"
          @change="hangldeCounts"
          :border="false"
          type="textarea"
          rows="6"
          max-length="200"
          placeholder="请描述投诉问题说明（必填）"
        />

        <div class="content">
          <template v-for="(item, index) in imageList" :key="item">
            <div class="img-item">
              <img class="img" :src="commonStore.img_domain + item" />
              <img
                class="close"
                src="@/assets/icons/close.png"
                @click="handleDelImg(index)"
              />
            </div>
          </template>

          <nut-uploader
            url="#"
            :before-upload="beforeUpload"
            accept="image/*"
            v-show="imageList.length < 3"
            multiple
          ></nut-uploader>
        </div>
        <div class="cont-tips">一次最多可以上传三张图片</div>
      </div>
    </div>
    <div class="container">
      <div class="tips flex flexC flexBetween">
        <div class="flex flexC">
          <div>联系方式</div>
        </div>
      </div>
      <nut-form :model-value="formData" :rules="rules" ref="ruleForm">
        <nut-form-item
          label="联系人"
          style="color: #000"
          required
          prop="contact_person"
        >
          <input
            class="nut-input-text"
            placeholder="请输入联系人姓名"
            type="text"
            error-message="请输入联系人姓名"
            v-model="formData.contact_person"
          />
        </nut-form-item>
        <nut-form-item
          label="联系方式"
          style="color: #000"
          prop="contact_phone"
          required
          :rules="[
            {
              regex:
                /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
              message: '手机号码填写不正确',
            },
          ]"
        >
          <input
            class="nut-input-text"
            placeholder="请输入联系电话"
            type="text"
            error-message="请输入联系电话"
            v-model="formData.contact_phone"
          />
        </nut-form-item>
      </nut-form>
      <div class="bg-btn-box">
        <nut-button
          block
          type="primary"
          color="linear-gradient(to right, #3EBD33, #9FDF4F)"
          @click="confirmBtn"
          >提交</nut-button
        >
      </div>
    </div>

    <myDialog
      ref="myDialogRef"
      :options="receptData"
      @confirm="confirm"
    ></myDialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, onBeforeMount, onMounted, ref } from "vue";
import { getAssetsFile, isRes } from "@/utils/pub-use";
import { getListApi, submitFeedbackApi } from "@/api/feedback/index";
import CARD0 from "./components/card0.vue";
import CARD1 from "./components/card1.vue";
import myDialog from "./components/dialog.vue";
import { getOSTokenApi, uploadImgApi } from "@/api/addstart";
import { getClient, ossPath } from "@/utils/alioss";
import useCommonStore from "@/store/common";
import { Toast } from "@nutui/nutui";
import { useRouter } from "vue-router";
const commonStore = useCommonStore();
const myDialogRef = ref<InstanceType<typeof myDialog>>();
const disabled = ref<boolean>(false);
const counts = ref<number>(0);
const hangldeCounts = (n: string) => {
  var txtVal = n.length;

  counts.value = 200 - txtVal;
};
const imageList = ref<any[]>([]);
let formData: any = ref({
  content: "",
  contact_person: "",
  contact_phone: "",
  order_id: "",
});
const ruleForm = ref<any>(null);
const rules = {
  contact_person: [{ required: true, message: "请输入联系人" }],
};
const handleDelImg = (index: any) => {
  imageList.value.splice(index, 1);
};
//----------------------------------------------------------------获取列表----------------------------------------------------------------
let receptData: any = ref({});
const getList = async () => {
  let res = await getListApi({
    page: 1,

    pagesize: 9999,
  });
  if (isRes(res)) {
    receptData.value = res.result;
  }
};
getList();

const openMyDialogRef = () => {
  myDialogRef.value?.openDialog();
};

let currentSelect: any = ref();
const confirm = (payload: any) => {
  if (payload) {
    currentSelect.value = payload;
    myDialogRef.value?.closeDialog();
  }
};

const credentials = ref<any>({
  securityToken: "",
  accessKeySecret: "",
  accessKeyId: "",
});
async function uploadImg(imgfile: File) {
  const res = await uploadImgApi({ imgfile });
  if (res.code == 0) {
    const { img_key } = res.result;
    imageList.value.push(img_key);
  }
}

const beforeUpload = (fileList: File[]) => {
  // uploadImg(fileList[0]);
  uploadOSS(fileList[0], "image");

  return new Promise((resolve) => {
    resolve(fileList);
  });
};

// 接口：获取OSS Token
async function getOSSToken() {
  const res = await getOSTokenApi();
  if (res.code == 0) {
    const { accessKeyId, accessKeySecret, securityToken } =
      res.result.credentials;
    credentials.value.accessKeyId = accessKeyId;
    credentials.value.accessKeySecret = accessKeySecret;
    credentials.value.securityToken = securityToken;
  }
}
getOSSToken();
async function uploadOSS(file: any, fileType: any) {
  var imgUrl = ossPath(file, fileType);
  getClient(
    credentials.value.accessKeyId,
    credentials.value.accessKeySecret,
    credentials.value.securityToken
  )
    .multipartUpload(imgUrl, file)
    .then((res: any) => {
      if (res.res.statusCode == 200) {
        var pathurl = res.name.replace("image/", "");
        imageList.value.push(pathurl);
      }
    });
}
const router = useRouter();
const confirmBtn = async () => {
  if (!currentSelect.value) {
    Toast.warn("请选择订单");
    return;
  }
  if (formData.value.content) {
    ruleForm.value.validate().then(async ({ valid, errors }: any) => {
      if (valid) {
        formData.value.order_id = currentSelect.value;
        formData.value.imgs = imageList.value;
        let res = await submitFeedbackApi(formData.value);
        if (isRes(res)) {
          router.push("/center");
        }
      }
    });
  } else {
    Toast.warn("请填写投诉内容");
  }
};
</script>
<style scoped lang="scss">
.warp {
  background: #f8f9fa;
  height: 100%;
  [v-cloak] {
    display: none !important;
  }

  .warp-content {
    padding: 30px 30px 0px 30px;

    .title {
      font-size: 28px;
      color: #000000;
      padding-bottom: 23px;
    }
  }
  .container {
    background: #fff;
    margin-bottom: 20px;
    padding: 30px 30px;
    .tips {
      color: #000000;
      font-size: 32px;
      font-weight: bold;
      .tips-nums {
        color: #999;
        font-size: 24px;
      }
    }
    .container-con {
      .nut-input {
        padding: 0 !important;
        width: 100% !important;
      }
    }
    :deep(.input-text) {
      width: 100% !important;
      height: 200px;
    }
    .cont-tips {
      color: #999;
      font-size: 24px;
      padding-top: 30px;
    }
    .content {
      display: flex;
      flex-wrap: wrap;

      .img-item {
        position: relative;
        margin: 0 20px 20px 0;
        width: 30%;

        .img {
          display: block;
          width: 100%;
          height: 200px;
        }

        .close {
          position: absolute;
          top: -8px;
          right: -8px;
          width: 36px;
        }
      }
    }
  }
}
</style>
